// import RSA from '../../tools/rsa.js';

export default class HttpUtils {
    static getHeaders(url, params, config = {}, method) {
        // 是否需要加签
        // const rsa_headers = config.encrypt ? this.getRsaHeaders(url, params, method) : {};
        config.headers = config.headers || {}

        if (global.$util.Storage.getToken()) {
            config.headers['Authorization'] = 'Bearer ' + global.$util.Storage.getToken() // 用户token
        }
        const myHeader = Object.assign({}, config.headers)
        return {
            'content-type': 'application/json',
            'device': global.$util.Storage.getPlatform() || '', // 设备唯一标识
            'platform': 'mini', // 小程序标识
            // 'weChatVersion':global.$util.Config.miniVersion,//小程序版本号
            'deviceVersion': wx.getSystemInfoSync().system || '', // 系统版本号
            // 'Authorization': 'Bearer ' + global.$util.Storage.getToken() || '', // 用户token
            ...myHeader,
            // PENNYWORTH_BRANCH:"exchange"
            // ...rsa_headers
        }
    }

    static get(url, params, config = {}) {
        return this.request(url, params, config, 'get')
    }

    static post(url, params, config = {}) {
        return this.request(url, params, config, 'post')
    }

    static uploadImage(url, params, config = {imgCount: 9}) { // 上传图片接口封装
        const headers = this.getHeaders(url, params, config, 'post');
        const isShowLoading = this.showLoading(config)
        // 因为多张图片且数量不定，这里遍历生成一个promiseList
        return new Promise(resolve => {
            wx.uploadFile({
                url,
                filePath: params.tempFilePaths,
                name: 'file',
                header: headers,
                formData: {
                    ...headers
                },
                success(res) {
                    let fileInfo = JSON.parse(res.data);
                    resolve(fileInfo)
                },
                fail(res) {
                    let fileInfo = JSON.parse(res.data)
                    resolve(fileInfo)
                },
                complete(res) {
                    if (isShowLoading) {
                        global.$util.Tool.hideLoading();
                    }
                }
            })
        })
    }

    static request(url, params, config, method) { // 接口请求封装
        params = params || {}
        let sysInfo = global.$util.Storage.sysInfo() || {}
        if (sysInfo) {
            params = {
                ...params,
                device: sysInfo.model,// 手机型号
                wechatVersion: sysInfo.version,// 微信版本
                systemVersion: params.systemVersion===undefined? sysInfo.system:params.systemVersion, // 系统版本
            }
        }
        const headers = this.getHeaders(url, params, config, method)
        return new Promise((resolve, reject) => {
            wx.request({
                url: url,
                data: params,
                method: method,
                header: headers,
                success: function (res) {
                    if (res.data.code === 200) {
                        console.log('請求成功')
                        resolve(res);
                    } else {
                        wx.showToast({
                            title: res.data.msg,
                            icon: 'none',
                            duration: 2000
                        })
                    }
                },
                fail: function (res) {
                    console.log('失敗')
                    reject(res.data);
                },
                complete: function (res) {

                }
            });
        })
    }

    // 获取验签header
    // static getRsaHeaders(url, params, method) {
    //     let rsa_headers = {};
    //     console.log(`对${url}进行加签处理`);
    //     rsa_headers = RSA.sign(params);
    //     if (method.toUpperCase() == 'POST') {
    //         rsa_headers = RSA.sign(this.query2Object(url));
    //     }
    //     return rsa_headers;
    // }

    static query2Object(str) {
        let url = str || document.URL;
        // removeURLAnchor
        url.indexOf('#') > 0 && (url = url.substring(0, url.indexOf('#')))
        let e = {},
            t = url,
            o = t.split('?').slice(1).join('');
        if (o.length < 3) {
            return e;
        }
        for (let n = o.split('&'), i = 0; i < n.length; i++) {
            let r = n[i], d = r.indexOf('=');
            if (!(0 > d || d === r.length - 1)) {
                let p = r.substring(0, d), s = r.substring(d + 1);
                0 !== p.length && 0 !== s.length && (e[p] = decodeURIComponent(s));
            }
        }
        return e;
    }

    static showLoading(config) {
        if (config.isShowLoading !== false) {
            return true
        } else {
            return false
        }
    }
}